import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

import { fetchUserInfo } from '@/api/system';
import { UserModel } from '@/models/UserModel';
import storage, { TOKEN } from '@/utils/StorageUtils';

export interface UserStore {
  clear: () => void;
  refreshUser: () => void;
  setUser: (token: string, data: UserModel) => void;
  token?: string;
  userInfo?: UserModel;
}

const userStore = create<UserStore>()(
  devtools(set => ({
    clear: () => {
      storage.remove(TOKEN);
      set({ token: undefined, userInfo: undefined });
    },
    refreshUser: async () => {
      const { data } = await fetchUserInfo();
      set({ userInfo: data });
    },
    setUser: (token: string, data: UserModel) => {
      storage.set(TOKEN, token);
      set({ token, userInfo: data });
    },
    token: storage.get(TOKEN) as string,
    userInfo: undefined,
  })),
);

export default userStore;
